package com.cutefool.zero.code.admin.dictionary.web;

import com.cutefool.core.kits.util.Lists;
import com.cutefool.core.objects.Select;
import com.cutefool.core.res.Response;
import com.cutefool.dsl.mybatis.core.dsl.builder.QueryDsl;
import com.cutefool.dsl.mybatis.core.dsl.operation.CuteCurdOperation;
import com.cutefool.rds.enums.RdsFieldType;
import com.cutefool.zero.code.admin.consts.Constants;
import com.cutefool.zero.code.admin.dictionary.dto.ColumnType;
import com.cutefool.zero.code.core.domain.DictionaryItem;
import com.cutefool.zero.code.core.query.DictionaryQuery;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping(Constants.API_PREFIX)
public class DictionaryController {

    @Resource
    private CuteCurdOperation<DictionaryItem> cuteCurdOperation;

    @GetMapping("/select/dictionary-envs")
    public Response<List<Select<?>>> envs() {
        return Response.ok(this.doSelects(Constants.DICTIONARY_DEFINE_ENV));
    }

    @GetMapping("/select/dictionary-sync-modes")
    public Response<List<Select<?>>> modes() {
        return Response.ok(this.doSelects(Constants.DICTIONARY_DEFINE_SYNC_MODE));
    }

    @GetMapping("/select/dictionary-db-sources")
    public Response<List<Select<?>>> sources() {
        return Response.ok(this.doSelects(Constants.DICTIONARY_DEFINE_DBMS_SOURCE));
    }

    @GetMapping("/select/dictionary-db-types")
    public Response<List<Select<?>>> types() {
        return Response.ok(this.doSelects(Constants.DICTIONARY_DEFINE_DB_TYPE));
    }

    @GetMapping("/select/dictionary-column-types")
    public Response<List<ColumnType>> columnTypes() {
        RdsFieldType[] values = RdsFieldType.values();
        return Response.ok(Stream.of(values)
                .map(e -> {
                    ColumnType columnType = new ColumnType();
                    columnType.setName(e.getName());
                    columnType.setDescription(e.getDescription());
                    columnType.setValue(e.getJdbcType().name());
                    return columnType;
                }).collect(Collectors.toList()));
    }


    private List<Select<?>> doSelects(String defineCode) {
        DictionaryQuery query = new DictionaryQuery();
        query.setDefineCode(defineCode);
        DictionaryItem instance = DictionaryItem.instance();
        QueryDsl<DictionaryItem> queryDsl = QueryDsl.newInstance(instance, query).selects(instance.table().code, instance.table().name);
        List<DictionaryItem> entities = this.cuteCurdOperation.list(queryDsl);
        // TODO 增加缓存
        return Lists.empty(entities).stream().map(e -> new Select<>(e.getName(), e.getCode())).collect(Collectors.toList());
    }
}
